<?php
/**
 * User: zhengze
 * Date: 2019/7/30
 * Time: 20:33
 */

namespace app\api\job;

use app\common\model\AdminActionLog;
use app\api\model\Member_actionLog;
use think\Exception;
use think\facade\Log;
use think\queue\Job;

class WriteActionLog
{
    protected $max_fail_num = 3;

    /**
     * 消费队列程序（这里的方法名和传入参数都是规定好了的）
     * @param Job $job 注入对象，队列对象
     * @param string $data 约定队列传递的数据。String类型
     */
    public function fire(Job $job, $data)
    {
//        echo "\n" . date("Y-n-j H:i:s") . "执行写日志任务\n";
        //执行发送邮件
        $isJobDone = $this->_writeActionLog($data);
        try {
            //如果发送成功  就删除队列
            if ($isJobDone) {
                print ("{$data['create_date']}-写日志任务执行成功,删除任务\n");
                $job->delete();
            } else {
                //如果执行到这里的话 说明队列执行失败  如果失败三次就删除该任务  否则重新执行
                print ("写日志任务执行失败!\n");
                if ($job->attempts() > $this->max_fail_num) {
                    print ("失败次数超过{$this->max_fail_num}次,删除任务\n");
                    $job->delete();
                } else {
                    $job->release(); //重发任务
                    print ("失败,重新执行!第" . $job->attempts() . "次重新执行!\n");
                }
            }
        } catch (Exception $e) {
            $this->_saveLog($e);
        }
    }

    /**
     * 写入数据库
     * @param $data
     * @return bool
     */
    private function _writeActionLog($data)
    {
        $res = [];
        if ($data['module'] == 'admin') {
            $res = AdminActionLog::instance()->insert($data);
        }
        if ($data['module'] == 'api') {
            $res = Member_actionLog::instance()->insert($data);
        }
        return $res;
    }

    /**
     * 保存异常日志
     * @param $data
     * @return bool
     */
    private function _saveLog($e)
    {
        $log = $e->getMessage() . "\n";
        $trace = $e->getTrace();
        foreach ($trace as $key => $value) {
            if (!empty($value['file']) && !empty($value['line'])) {
                $log .= sprintf("%s (%s) %s", $value['file'], $value['line'], "\n");
            }
        }
        Log::error($log);
    }
}